package com.lzy.chat.d_controller;


import com.lzy.chat.c_service.Exception.Exceptions;
import com.lzy.chat.c_service.Exception.ServiceException;
import com.lzy.chat.e_util.JsonResult;
import com.lzy.chat.g_annotation.NeedToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("file")
public class FileController extends BaseController {

    @Value("${file-save-path}")
    private String fileSavePath;

    @NeedToken
    @RequestMapping("upload")
    public JsonResult<Map<String, String>> upload(MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) throw new ServiceException(Exceptions.FileEmptyException);
        String filename = getMd5(file);
        File localFile = new File(fileSavePath + filename);
        if (!localFile.exists()) {
            boolean isSuccess = localFile.mkdirs();
            if (!isSuccess) {
                System.out.println("文件创建失败!");
            }
        }
        file.transferTo(localFile);
        Map<String, String> map = new HashMap<>();
        String url = request.getScheme() + "://" + request.getServerName() + ":" +
                request.getServerPort() + "/images/" + filename;
        map.put("url", url);
        return new JsonResult<>(ok, map);
    }

    @NeedToken
    @RequestMapping("isHas")
    public JsonResult<Map<String, String>> isHas(String hash, HttpServletRequest request) {
        File file = new File(fileSavePath + hash);
        String url = request.getScheme() + "://" + request.getServerName() + ":" +
                request.getServerPort() + "/images/" + hash;
        HashMap<String, String> map = new HashMap<>();
        if (file.exists()) {
            map.put("has", "true");
            map.put("path", url);
        } else {
            map.put("has", "false");
        }
        return new JsonResult<>(ok, map);
    }

    public String getMd5(MultipartFile file) throws IOException {
        //file->InputStream,生成md5
        //对字符串生成md5
        return DigestUtils.md5DigestAsHex(file.getInputStream());
    }
}
